<!-- 虚拟库房 -->
<template>
  <div class="container">
    <el-row :gutter="20">
      <el-col :span="4">
        <el-card style="overflow-y: scroll">
          <el-tree :data="hosuseCabinetTree" :props="defaultProps" @node-click="handleNodeClick">
            <span slot-scope="{ node }" style="font-size: 14px">
              <i v-if="node.level == 1" class="iconfont icon-shouye"></i>
              <i v-else-if="node.level == 2" class="iconfont icon-wenjianguanli"></i>
              <i v-else class="iconfont icon-0-52"></i>
              <span style="margin-left: 10px">{{ node.label }}</span>
            </span>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="20" style="padding-left: 0">
        <el-card class="box-card" style="overflow-y: scroll">
          <el-empty description="请选择库房/密集架进行查看档案/盒的数据" v-if="cabinetList.length == 0"></el-empty>
          <div class="cabint-body" v-for="(item, index) in cabinetList" :key="index" :style="{
            height: zoomStyle.cabintBodyHeight + 'vh',
          }" style="transition: height 0.5s ease-in-out">
            <el-row>
              <el-col :span="20">
                <div style="margin: 10px auto; width: 60%; text-align: center">
                  <span style="font-weight: 700">{{ item.deviceName }}</span> 共<span class="heightLight-text">{{
                    item.children.length }}</span>列
                </div>
                <div class="cabint" :ref="`cabint${index}`">
                  <div class="cabint-item" ref="cabintItem" :style="{
                    width: getMjjboxWidth(item.children),
                    'margin-left': getMarginLeft(item.children, index),
                  }">
                    <div v-for="(x, i) in item.children" :key="x.deviceId" :ref="'mjj' + x.colNo" :class="[
                      'mjj-box',
                      'mjj' + x.colNo,
                      {
                        'move-initial': x.moveFlag == 0,
                        'move-right': x.moveFlag == 1,
                        'move-left': x.moveFlag == -1,
                        isActive: x == currentIndex,
                      },
                    ]" :style="{
                      transform:
                        x.moveFlag === 2 || x.moveFlag === -2
                          ? `translateX(${(i - item.children.findIndex((x) => x.fixedFlag === 1)) * 0.2
                          }rem)`
                          : '',
                      transition: moveStatus ? 'transform 10s' : '',
                      width: zoomStyle.mjjBoxWidth + 'rem',
                      '--gradient-start': 100 - percentage(x) + '%',
                    }" @click="oneSelectMjj(x, item)">
                      <em class="mjj-text" :style="{
                        top: lessThan90(percentage(x)) + '%',
                        fontSize: zoomStyle.mjjTextSize + 'rem',
                      }">{{ percentage(x) }}%</em>
                      <em class="mjj-text" :style="{
                        top: '27%',
                        color: '#ff0604',
                        fontSize: zoomStyle.colTextSize + 'rem',
                      }" style="font-family: DSDIGIT">{{ formattedFourDigitNumber(x.colNo) }}</em>
                      <img v-if="x.fixedFlag == 1" :src="`${item.fixedColUrl
                        ? `${uploadURL}/mjj/${item.fixedColUrl}`
                        : getLocalImageUrl(x.fixedFlag)
                        }`" class="mjj-img no-select" style="width: 100%; height: 100%" />
                      <img v-else :src="`${item.moveColUrl
                        ? `${uploadURL}/mjj/${item.moveColUrl} `
                        : getLocalImageUrl(x.fixedFlag)
                        }`" class="mjj-img no-select" style="width: 100%; height: 100%" />
                    </div>
                  </div>
                </div>

                <div class="move-button" v-show="zoomStyle.showMoveButton">
                  <el-button type="primary" :disabled="canClick" @click="handleVent" round
                    v-show="showMoveButton('vent')" class="iconfont icon-a-28tongfengfengshan">
                    通风</el-button>
                  <el-button type="primary" :disabled="canClick" @click="handleLeft(colItem, cabinetDevice)" round
                    v-show="showMoveButton('moveLeft')" class="iconfont icon-zuoyi">
                    左移</el-button>
                  <el-button type="primary" :disabled="canClick" @click="handleOpenSelf(colItem, cabinetDevice)"
                    v-show="showMoveButton('openCol')" round class="iconfont icon-kaimen">
                    打开</el-button>
                  <el-button type="primary" :disabled="canClick" @click="handleCloseSlef" round
                    v-show="showMoveButton('close')" class="iconfont icon-guanmen">
                    合架</el-button>

                  <el-button type="primary" :disabled="canClick" @click="handleRight(colItem, cabinetDevice)"
                    class="iconfont icon-youyi" round v-show="showMoveButton('moveRight')">
                    右移</el-button>
                  <el-button type="primary" :disabled="canClick" @click="handleUnLock(LockFlag ? 'lock' : 'unlock')"
                    :class="['iconfont', LockFlag ? 'icon-suoding' : 'icon-jiesuo']" round
                    v-show="showMoveButton(LockFlag ? 'lock' : 'unlock')">
                    {{ LockFlag ? '锁定' : '解锁' }}</el-button>
                  <el-button type="primary" :disabled="canClick" @click="handleSleep()"
                    :class="['iconfont', sleepFlag ? 'icon-xiumian' : 'icon-huanxing']" class="iconfont" round
                    v-show="showMoveButton('sleep')">
                    {{ sleepFlag ? '休眠' : '唤醒' }}</el-button>
                </div>
              </el-col>
              <el-col :span="4">
                <div style="height: 100%; width: 16%; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)" class="info-box">
                  <ul :style="[{ 'font-size': zoomStyle.infoListSize + 'px' }]"
                    style="transition: height 0.5s ease-in-out" class="info-list">
                    <li style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap">
                      <span style="float: left">
                        {{ colData(item, 'name') }}
                      </span>
                      <!-- <span style="float: right"><el-button link>查看详情</el-button></span> -->
                    </li>
                    <li v-show="showWater">
                      架内温度:
                      <i class="heightLight-text">{{
                        getHumiture && getHumiture.temp !== '' ? getHumiture.temp.toFixed(1) : 0
                      }}</i>°C
                    </li>
                    <li v-show="showWater">
                      架内湿度:
                      <i class="heightLight-text">{{
                        getHumiture && getHumiture.humi !== '' ? getHumiture.humi.toFixed(1) : 0
                      }}</i>%RH
                    </li>
                    <li>
                      档案:
                      <i class="heightLight-text"> {{ colData(item, 'archiveCount') }} </i>件
                    </li>
                    <li>
                      档案盒:
                      <i class="heightLight-text">
                        {{ colData(item, 'boxCount') }}
                      </i>
                      盒
                    </li>
                    <li>
                      总容量:
                      <i class="heightLight-text"> {{ colData(item, 'allDivWidth') }} </i>
                      CM
                    </li>
                    <li>
                      剩余空间:
                      <i class="heightLight-text">
                        {{ colData(item, 'surplusSpace') }}
                        <!-- {{ showColItemData ? surplusSpace(item) : 100 - percentage(colItem) }} -->
                        %</i>
                    </li>
                    <transition name="el-fade-in-linear">
                      <li v-show="showWater">
                        <div class="water-circle" id="reporterRatio">
                          <div class="water water-level-10"></div>
                        </div>
                      </li>
                    </transition>
                    <transition name="el-fade-in-linear">
                      <li v-show="isShowLeftAndRight(item)">
                        <el-button @click="allColbody()" style="margin-bottom: 10px">查看整列档案/盒</el-button>

                        <el-button-group style="display: flex; justify-content: center; align-items: center">
                          <el-button @click="openDetail('1', colItem)">{{
                            zytypebutton == 0 ? 'A面' : '左面'
                          }}</el-button>
                          <el-button @click="openDetail('2', colItem)">{{
                            zytypebutton == 0 ? 'B面' : '右面'
                          }}</el-button>
                        </el-button-group>
                      </li>
                    </transition>
                  </ul>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <colDetails ref="colDetails" :colItem="colItem" :showClick="false" @getCabinetCol="getCabinetCol"></colDetails>
    <BoxPositionColDetails ref="BoxPositionColDetails" :showClick="false" :colItem="colItem"></BoxPositionColDetails>
    <el-dialog :title="colItem.colName + '内容详情'" v-model="dialogVisible" width="60%" modal draggable
      :close-on-click-modal="false" :append-to-body="true" :before-close="handleClose">
      <colAmsTable></colAmsTable>
    </el-dialog>
    <seeColData ref="seeColData"></seeColData>
  </div>
</template>

<script>
import move from '@/utils/move'
import Decimal from 'decimal.js'
import { getButtons, cabinetGeneral } from '@/api/openApi'
import { cabinetTree, virtualRepositoryCabinet, allCabinet } from '@/api/rfid/virtualRepository'
import colDetails from './colDetails.vue'
import colAmsTable from './colAmsTable.vue'
import seeColData from '@/components/seeColData.vue'
import BoxPositionColDetails from './BoxPositionColDetails.vue'
export default {
  name: 'VirtualHouse',
  components: { colDetails, colAmsTable, seeColData, BoxPositionColDetails },
  data() {
    return {
      showColItemData: true,
      hosuseCabinetTree: [],
      cabinetList: [],
      currentIndex: null,
      colItem: {},
      cabinetDevice: {},
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      lastClickTime: 0,
      dialogVisible: false,
      zoomStyle: {
        cabintBodyHeight: 0,
        mjjBoxWidth: 0.6,
        infoListSize: 14,
        showMoveButton: false,
      },
      showWater: false,
      moveClass: '',
      isMoved: false,
      observer: null,
      hasMoved: false, // 已经移动过了的标识
      moveArr: [],
      canClick: false, // 允许点击
      LockFlag: true, //解锁标识
      sleepFlag: true, //休眠标识
      ButtonList: [], //获取密集架的按钮
      VentFlag: true, //通风的标识
      getHumiture: {
        temp: 0,
        humi: 0,
      },
      zytypebutton: 0,
      moveStatus: false, //默认移动的状态
    }
  },
  computed: {
    formattedFourDigitNumber() {
      /**
       * 格式化数字为四位数。如果数字本身是1-999之间的数，
       * 则在其前面补足零至四位；如果是四位数或以上，则直接返回该数字。
       */

      return function (val) {
        const numStr = String(val)
        const paddingLength = 4 - numStr.length
        // 确保只对不足四位的数字进行补零
        return paddingLength > 0 ? `0`.repeat(paddingLength) + numStr : numStr
      }
    },
    // 当前列的容量
    colData() {
      return function (val, flag) {
        const length = val.children.filter((x) => x.cabinetId == this.colItem.cabinetId).length
        if (length != 0) {
          const col = val.children.filter((x) => x.colNo == this.colItem.colNo)[0]

          switch (flag) {
            case 'name':
              return col.colName

            case 'archiveCount':
              return col.archiveCount

            case 'boxCount':
              return col.boxCount

            case 'allDivWidth':
              return col.allDivWidth

            case 'surplusSpace':
              return new Decimal(100).sub(new Decimal(this.percentage(col)))
          }
        } else {
          switch (flag) {
            case 'name':
              return val.deviceName

            case 'archiveCount':
              return val.archiveCount

            case 'boxCount':
              return val.boxCount

            case 'allDivWidth':
              return val.allDivWidth

            case 'surplusSpace':
              return this.surplusSpace(val)
          }
        }
      }
    },
    // 剩余空间
    surplusSpace() {
      // 剩余空间 = (1- (盒总宽总计 / 库位总宽度))*100%
      return function (val) {
        if (val) {
          const allDivWidth = val.allDivWidth === 0 ? 1 : val.allDivWidth
          // 剩余空间
          const remainingSpace = Decimal(1)
            .sub(new Decimal(val.allBoxWidth).div(new Decimal(allDivWidth)))
            .mul(100)
            .toFixed(1)
          document.documentElement.style.setProperty(
            '--remaining-space',
            35 - ((90 - remainingSpace) / 100) * (35 + 55) + '%'
          )

          return remainingSpace
        }
      }
    },
    // 密集架中的百分比
    percentage() {
      return function (val) {
        if (val) {
          const cmPageNo = JSON.parse(localStorage.getItem('cmPageNo'))

          /**
           * val.pageNoCount 档案的页数  cmPageNo  定义的档案多少页为一厘米
           * val.pageNoCount / cmPageNo  档案一共占据了多少里面
           * val.allBoxWidth + val.pageNoCount / cmPageNo  档案盒和档案一共占据的宽度
           */
          var width
          if (cmPageNo) {
            // val.allBoxWidth + val.pageNoCount / cmPageNo
            width = new Decimal(val.allBoxWidth).add(
              new Decimal(val.pageNoCount).div(new Decimal(cmPageNo))
            )
          } else {
            width = val.allBoxWidth
          }
          // 除数做判断，不能为0
          const allDivWidth = val.allDivWidth === 0 ? 1 : val.allDivWidth

          return new Decimal(width).div(new Decimal(allDivWidth)).mul(100).toFixed(1)
        }
      }
    },

    // 计算百分比不能超过90%，防止大于90之后超出屏幕
    lessThan90() {
      return function (val) {
        /**
         * val实际是percentage()的值，也就是已经档案盒已经用的多少
         * 此处用于定位距顶的距离。即top的值，经测试不可以大于10%否则会超出屏幕，所以在此处限制
         * 不能大于10% 不能超过98%
         */
        return (100 - val >= 10 ? 100 - val : 10) <= 98 ? (100 - val >= 10 ? 100 - val : 10) : 98
      }
    },
  },
  filters: {},
  props: {},
  watch: {},
  methods: {
    /** 密集架移动操作逻辑开始 =============================================== */
    // 打开的逻辑
    async handleOpenSelf(item, device) {
      const result = await this.handleMethod('openCol', this.cabinetList[0])
      if (result) {
        if (this.VentFlag) {
          if (item.moveFlag == 0) {
            if (item.colNo > device.fixedColNo) {
              if (item.moveFlag == 0) {
                this.handleRightAnimation(item, device)
              } else if (item.moveFlag == 1) {
                this.handleLeftAnimation(item, device)
              }
            } else if (item.colNo < device.fixedColNo) {
              if (item.moveFlag == 0) {
                this.handleLeftAnimation(item, device)
              } else if (item.moveFlag == -1) {
                this.handleRightAnimation(item, device)
              }
            }
          } else {
            this.$message.error('密集架已经在打开状态了，请先合架再打开')
          }
        } else {
          this.$message.error('请先合架，之后在进行操作')
        }
      } else {
        this.$message.error('接口请求失败，请检查后重新尝试···')
      }
    },
    // 左移的逻辑
    async handleLeft(item, device) {
      const result = await this.handleMethod('moveLeft', this.cabinetList[0])
      if (result) {
        if (this.VentFlag) {
          if (this.LockFlag) {
            let needMove = this.cabinetList[0].children
            let loopCount = 0 // 添加计数器
            this.canClick = true

            const index = needMove.findIndex((x) => x.colNo === item.colNo)
            // 获取固定列的索引
            const fixedIndex = needMove.findIndex((x) => x.fixedFlag === 1)
            if (item.colNo > device.fixedColNo) {
              // console.log('在固定列右边')
              for (let i = 0; i < index + 1; i++) {
                let isIWithinRange =
                  fixedIndex < index ? fixedIndex < i && i <= index : index <= i && i <= fixedIndex
                if (needMove[i].moveFlag == 1 && isIWithinRange) {
                  loopCount++
                  setTimeout(() => {
                    needMove[i].moveFlag = 0
                  }, (loopCount - 1) * 1000)
                }
              }
            } else if (item.colNo < device.fixedColNo) {
              // console.log('在固定列z边')
              if (index !== -1) {
                for (let i = 0; i < index + 1; i++) {
                  if (needMove[i].moveFlag !== -1) {
                    loopCount++
                    setTimeout(() => {
                      needMove[i].moveFlag = -1
                    }, (loopCount - 1) * 1000)
                  }
                }
              }
            } else if (item.colNo == undefined) {
              this.$message.error('请选择密集架，之后再进行操作')
            }
            // 等待动画时间结束之后
            setTimeout(() => {
              this.canClick = false
            }, loopCount * 1000)
          } else {
            this.$message.error('请先锁定密集架')
          }
        } else {
          this.$message.error('请先合架，之后在进行操作')
        }
      } else {
        this.$message.error('接口请求失败，请检查后重新尝试···')
      }
    },
    // 左移的动画
    async handleLeftAnimation(item, device) {
      if (this.LockFlag) {
        let needMove = this.cabinetList[0].children
        let loopCount = 0 // 添加计数器
        this.canClick = true

        const index = needMove.findIndex((x) => x.colNo === item.colNo)
        // 获取固定列的索引
        const fixedIndex = needMove.findIndex((x) => x.fixedFlag === 1)
        if (item.colNo > device.fixedColNo) {
          // console.log('在固定列右边')
          for (let i = 0; i < index + 1; i++) {
            let isIWithinRange =
              fixedIndex < index ? fixedIndex < i && i <= index : index <= i && i <= fixedIndex
            if (needMove[i].moveFlag == 1 && isIWithinRange) {
              loopCount++
              setTimeout(() => {
                needMove[i].moveFlag = 0
              }, (loopCount - 1) * 1000)
            }
          }
        } else if (item.colNo < device.fixedColNo) {
          // console.log('在固定列左边')
          if (index !== -1) {
            for (let i = 0; i < index + 1; i++) {
              if (needMove[i].moveFlag !== -1) {
                loopCount++
                setTimeout(() => {
                  needMove[i].moveFlag = -1
                }, (loopCount - 1) * 1000)
              }
            }
          }
        } else if (item.colNo == undefined) {
          this.$message.error('请选择密集架，之后再进行操作')
        }
        // 等待动画时间结束之后
        setTimeout(() => {
          this.canClick = false
        }, loopCount * 1000)
      } else {
        this.$message.error('请先锁定密集架')
      }
    },
    // 右移的逻辑
    async handleRight(item, device) {
      const result = await this.handleMethod('moveRight', this.cabinetList[0])
      if (result) {
        if (this.VentFlag) {
          if (this.LockFlag) {
            let needMove = this.cabinetList[0].children
            let loopCount = 0 // 添加计数器
            this.canClick = true

            const index = needMove.findIndex((x) => x.colNo === item.colNo)
            if (item.colNo > device.fixedColNo) {
              // console.log('在固定列右边')
              for (let i = needMove.length - 1; i >= 0; i--) {
                if (needMove[i].moveFlag == 0 && index <= i) {
                  loopCount++
                  setTimeout(() => {
                    needMove[i].moveFlag = 1
                  }, (loopCount - 1) * 1000)
                }
              }
            } else if (item.colNo < device.fixedColNo) {
              // console.log('在固定列左边')
              for (let i = needMove.length - 1; i >= 0; i--) {
                if (needMove[i].moveFlag == -1 && index <= i) {
                  loopCount++
                  setTimeout(() => {
                    needMove[i].moveFlag = 0
                  }, (loopCount - 1) * 1000)
                }
              }
            } else if (item.colNo == device.fixedColNo) {
              this.$message.error('当前是固定列，请不要移动')
            }
            // 等待动画时间结束之后
            setTimeout(() => {
              this.canClick = false
            }, loopCount * 1000)
          } else {
            this.$message.error('请先锁定密集架')
          }
        } else {
          this.$message.error('请先合架，之后在进行操作')
        }
      } else {
        this.$message.error('接口请求失败，请检查后重新尝试···')
      }
    },
    // 右移的动画
    async handleRightAnimation(item, device) {
      if (this.LockFlag) {
        let needMove = this.cabinetList[0].children
        let loopCount = 0 // 添加计数器
        this.canClick = true

        const index = needMove.findIndex((x) => x.colNo === item.colNo)
        if (item.colNo > device.fixedColNo) {
          // console.log('在固定列右边')
          for (let i = needMove.length - 1; i >= 0; i--) {
            if (needMove[i].moveFlag == 0 && index <= i) {
              loopCount++
              setTimeout(() => {
                needMove[i].moveFlag = 1
              }, (loopCount - 1) * 1000)
            }
          }
        } else if (item.colNo < device.fixedColNo) {
          // console.log('在固定列左边')
          for (let i = needMove.length - 1; i >= 0; i--) {
            if (needMove[i].moveFlag == -1 && index <= i) {
              loopCount++
              setTimeout(() => {
                needMove[i].moveFlag = 0
              }, (loopCount - 1) * 1000)
            }
          }
        } else if (item.colNo == device.fixedColNo) {
          this.$message.error('当前是固定列，请不要移动')
        }
        // 等待动画时间结束之后
        setTimeout(() => {
          this.canClick = false
        }, loopCount * 1000)
      } else {
        this.$message.error('请先锁定密集架')
      }
    },
    // 合架
    async handleCloseSlef() {
      const result = await this.handleMethod('close', this.cabinetList[0])
      if (result) {
        this.VentFlag = true

        if (this.LockFlag) {
          // 将所有的密集架的位置都回到原位置
          let needMove = this.cabinetList[0].children
          let loopCount = 0 // 添加计数器
          this.canClick = true

          const fixedIndex = needMove.findIndex((x) => x.fixedFlag === 1) // 获取固定列的索引
          // 密集架左侧的关闭动画
          for (let i = fixedIndex; i >= 0; i--) {
            if (needMove[i].moveFlag == -1 || needMove[i].moveFlag == -2) {
              loopCount++
              setTimeout(() => {
                needMove[i].moveFlag = 0
              }, (loopCount - 1) * 1000)
            }
          }
          let loopCountLeft = loopCount
          // 密集架右侧侧的关闭动画
          loopCount = 0 //需要置空
          for (let i = fixedIndex; i < needMove.length; i++) {
            if (needMove[i].moveFlag == 1 || needMove[i].moveFlag == 2) {
              loopCount++
              setTimeout(() => {
                needMove[i].moveFlag = 0
              }, (loopCount - 1) * 1000)
            }
          }
          let maxValue = Math.max(loopCountLeft, loopCount)
          setTimeout(() => {
            this.canClick = false
          }, maxValue * 1000)
        } else {
          this.$message.error('请先锁定密集架')
        }
      } else {
        this.$message.error('接口请求失败，请检查后重新尝试···')
      }
    },
    // 通风的逻辑
    async handleVent() {
      let needMove = this.cabinetList[0].children //获取当前的密集架的详情
      const result = await this.handleMethod('vent', this.cabinetList[0]) //监测接口是否调通
      const CanVent = needMove.every((x) => x.moveFlag === 0) // 检查needMove中的moveFlag是否为0，为0则执行动画
      if (result) {
        this.VentFlag = false
        // 判断是否锁定
        if (this.LockFlag) {
          // 判断是否有密集架正在打开的状态
          if (CanVent) {
            let loopCount = 0 // 添加计数器
            this.canClick = true
            const fixedIndex = needMove.findIndex((x) => x.fixedFlag === 1) // 获取固定列的索引
            // 固定列左侧的动画
            // 左侧动画
            for (let i = 0; i < fixedIndex + 1; i++) {
              loopCount++
              setTimeout(() => {
                needMove[i].moveFlag = -2
              }, (loopCount - 1) * 1000)
            }
            let loopCountLeft = loopCount
            // 固定列右侧的动画
            // 重新将loopCount置空
            loopCount = 0
            for (let i = needMove.length - 1; i >= fixedIndex; i--) {
              loopCount++
              setTimeout(() => {
                needMove[i].moveFlag = 2
              }, (loopCount - 1) * 1000)
            }
            // 等待动画时间结束之后
            let maxValue = Math.max(loopCountLeft, loopCount)
            setTimeout(() => {
              this.canClick = false
            }, maxValue * 1000)
          } else {
            this.$message.error('请先合架，之后在进行操作')
            return
          }
        } else {
          this.$message.error('请先锁定密集架')
        }
      } else {
        this.$message.error('接口请求失败，请检查后重新尝试···')
      }
    },
    // 解锁
    async handleUnLock(method) {
      const result = await this.handleMethod(method, this.cabinetList[0])
      if (result) {
        this.LockFlag = !this.LockFlag

        if (this.LockFlag) {
          this.$message.success('解锁成功')
        } else {
          this.$message.warning('已锁定')
        }
      } else {
        this.$message.error('接口请求失败，请检查后重新尝试···')
      }
    },
    // 休眠
    handleSleep() {
      this.sleepFlag = !this.sleepFlag
      if (this.sleepFlag) {
        this.$message.success('已唤醒')
      } else {
        this.$message.warning('已休眠')
      }
    },

    // 获取密集架的按钮
    getMjjBtn(item) {
      getButtons({ brandCode: item.brandCode, version: item.verNo }).then((res) => {
        if (res.data.code == 0) {
          this.ButtonList = res.data.data
        } else {
          // 数组置空
          this.ButtonList = []
        }
      })
    },
    // 通用方法
    handleMethod(methods, data) {
      if (methods !== 'getHumiture') {
        this.moveStatus = true
      }
      let params = {
        storeCode: data.storeCode, //库码
        brandCode: data.brandCode, //品牌编码
        method: methods, // 通用方法的传参
        ip: data.deviceIp, //ip
        port: data.devicePort, //端口
        quNo: data.quNo, // 区号
        colNo: this.colItem.colNo, //列号
        zyNo: data.zyType, // 左右面
        leNo: data.leNum, //节数
        diyNo: data.divNum, //  层数
        version: data.verNo, //  版本协议
      }

      return cabinetGeneral(params)
        .then((res) => {
          if (res.data.code == 0) {
            if (methods === 'getHumiture') {
              this.getHumiture = res.data.data
            }
            return true
          } else {
            return false
          }
        })
        .catch((err) => {
          return false
        })

      // return true // 不使用接口的时候放开
    },

    /** ===============================================密集架移动操作逻辑结束 */
    // 根据接口显示需要移动的按钮
    showMoveButton(val) {
      return this.ButtonList.some((obj) => obj.method === val)
    },
    // 手动计算密集架盒子的宽度
    getMjjboxWidth(val) {
      return val.length > 10 ? `${val.length * 1.2}rem` : 'auto'
    },
    // 手动计算密集架距离左边的距离
    getMarginLeft(val, index) {
      this.$nextTick(() => {
        new move(this.$refs[`cabint${index}`][0])
      })
      if (val.length > 9) {
        const marginLeft = val.findIndex((x) => x.fixedFlag === 1) * 0.2
        setTimeout(() => {
          this.$refs[`cabint${index}`][0].scrollLeft = marginLeft * 192 + val.length * 10
        }, 200)
        return `${marginLeft}rem`
      } else {
        return '0'
      }
    },
    updateRemainingSpaceVar(value) {
      document.documentElement.style.setProperty('--remaining-space', value + '%')
    },
    // 判断是否显示左右面
    isShowLeftAndRight(item) {
      return item.children.filter((x) => x.cabinetId == this.colItem.cabinetId).length == 0
        ? false
        : true
    },
    initEcharts() { },
    async getLocalImageUrl(flag) {
      const imagePath = flag == 1 ? '@/assets/mjj_fix.png' : '@/assets/mjj_p.png'
      return await import(imagePath)

    },
    handleClose() {
      this.dialogVisible = false
    },
    // 单击点击事件
    oneSelectMjj(item, device) {
      this.zytypebutton = item.zyType
      this.showColItemData = false
      this.colItem = item
      this.cabinetDevice = device
      // 判断item与currentIndex ，相同的话，就将currentIndex置空
      if ((this.currentIndex ? this.currentIndex : '') == item) {
        this.currentIndex = null
      } else {
        this.currentIndex = item
      }
    },
    // 遍历数组
    // 查看当前列
    showCol() {
      if (!this.colItem) {
        this.$message.warning('请选择列之后 再进行查看')
      } else {
        this.dialogVisible = true
      }
    },
    // 双击选择装具
    dbSelectMjj(item) {
      this.colItem = item


      this.currentIndex = item
    },
    openDetail(flag, colItem) {
      if (colItem.posNum == null || colItem.posNum == 0) {
        // 证明没有盒定位标识
        this.$refs.colDetails.show(flag, colItem)
      } else {
        this.$refs.BoxPositionColDetails.show(flag, colItem)
      }
    },
    allColbody() {
      this.$refs.seeColData.show(this.colItem)
    },
    // 获取库房装具树
    getCabinetTree(data) {
      cabinetTree(data).then((res) => {
        if (res.data.code == 200) {
          // 将res.data.data转为数组
          this.hosuseCabinetTree = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },

    handleNodeClick(data, node) {
      // setTimeout(() => {
      //   this.$refs.cabint[6].scrollLeft = 800
      // }, 200)
      if (node.level == 1) {
        // 获取所有的装具
        this.showColItemData = true
        this.showWater = false
        this.zoomStyle = {
          cabintBodyHeight: 40,
          mjjBoxWidth: 0.6,
          infoListSize: 14,
          showMoveButton: false,
          mjjTextSize: 0.2,
          colTextSize: 0.1,
        }
        this.getAllCabinet(data.repositoryId)
      }
      if (node.level == 2) {
        this.showWater = true
        this.moveStatus = false //默认移动的状态
        this.showColItemData = true

        // 获取装具的列
        this.zoomStyle = {
          cabintBodyHeight: 70,
          mjjBoxWidth: 1.2,
          infoListSize: 16,
          showMoveButton: true,
          mjjTextSize: 0.3,
          colTextSize: 0.2,
        }

        this.getCabinetCol(data.deviceId)
      }
    },
    // 根据数据的长度生成长度一致，值为0的数组
    createArrayByLength(length) {
      this.moveArr.length = 0
      for (let i = 0; i < length; i++) {
        this.moveArr.push(0)
      }
      return this.moveArr
    },
    // 获取所有的装具
    getAllCabinet(repositoryId) {
      allCabinet(repositoryId).then((res) => {
        if (res.data.code == 200) {
          this.cabinetList = res.data.data
        } else {
          // 接口报错的时候清空数据
          this.cabinetList = []
          this.$message.error(res.data.message)
        }
      })
    },
    // 获取装具的列
    getCabinetCol(data) {
      virtualRepositoryCabinet(data)
        .then((res) => {
          if (res.data.code == 200) {
            this.cabinetList = []
            res.data.data.children = res.data.data.children.map((x) => {
              return {
                ...x,
                moveFlag: 0,
              }
            })
            this.cabinetList.push(res.data.data)
            this.createArrayByLength(res.data.data.children.length)
            this.getMjjBtn(res.data.data)
            // 获取密集架的温湿度
            this.handleMethod('getHumiture', this.cabinetList[0])
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
  },
  created() { },
  mounted() {
    this.getCabinetTree()
  },
}
</script>
<style lang="less" scoped>
.container {
  height: 90%;

  .el-row {
    height: 100%;

    .el-col {
      height: 100%;

      .el-card {
        height: 75vh;
      }
    }
  }
}

.box-card {
  width: 100%;

  .cabint-body {
    .cabint {
      margin: 0 auto 10px;
      height: 80%;
      overflow-x: auto;
      /* 允许横向滚动 */

      position: relative;

      /* 为绝对定位的子元素提供定位上下文 */
      .cabint-item {
        display: flex;
        justify-content: center;
        height: 80%;
        line-height: 80%;

        .mjj-box {
          position: relative;
          width: 0.6rem
            /* 100/192 */
          ;
          margin: 10px 2px;
          --gradient-start: var(--gradient-start);
          display: flex;
          justify-content: center;
          align-items: center;
        }

        .mjj-box::after {
          content: '';
          /* 伪元素必须有内容 */
          position: absolute;
          /* 绝对定位 */
          top: 0;
          /* 与容器顶部对齐 */
          left: 0;
          /* 与容器左侧对齐 */
          width: 100%;
          /* 覆盖图片的宽度 */
          height: 100%;
          /* 覆盖图片的高度 */

          background: linear-gradient(rgba(255, 255, 255, 0) var(--gradient-start),
              rgba(78, 166, 228, 0.6) 0%);
          /* 设置颜色和透明度，这里以半透明红色为例 */
          z-index: 1;
          /* 确保覆盖层在图片之上 */
        }
      }
    }
  }

  .isActive {
    filter: brightness(80%);
    /* 降低亮度 */
  }
}

.mjj-img {
  position: relative;
  max-width: 100%;
  height: auto;
}

.mjj-text {
  position: absolute;
  // 垂直水平居中
  left: 50%;
  color: #f2f2f2f2;
  transform: translate(-50%, -100%);
  font-size: 0.3rem
    /* 16/192 */
  ;
  font-weight: 700;
  z-index: 99;
}

.move-button {
  margin: 0 auto;
  width: 100%;
  text-align: center;

  // display: flex;
  // justify-content: space-around;
  i {
    display: inline-block;
    height: 0.3rem
      /* 50/192 */
    ;
    line-height: 0.3rem
      /* 50/192 */
    ;
    font-size: 0.3rem
      /* 50/192 */
    ;
    border-radius: 10px;
    cursor: pointer;
    padding: 10px 15px;
    background: #15a8ea;
    color: #fff;
  }

  img {
    margin: 0 10px;
    height: 100%;
  }
}

.info-box {
  position: absolute;
  right: 0%;
  opacity: 0;
  animation: bounceInRight 0.5s linear forwards;
}

.info-list {
  height: 100%;
  position: relative;

  li {
    padding: 10px;

    &:last-child {
      // 将它放在最下面
      position: absolute;
      left: 50%;
      bottom: 0;
      transform: translateX(-50%);
    }
  }
}

.heightLight-text {
  // 去除斜体
  font-style: normal;
  color: #15a8ea;
  font-weight: 700;
}

@keyframes bounceInRight {

  from,
  60%,
  75%,
  90%,
  to {
    animation-timing-function: cubic-bezier(0.215, 0.61, 0.355, 1);
  }

  0% {
    opacity: 0;
    transform: translate3d(3000px, 0, 0);
  }

  60% {
    opacity: 1;
    transform: translate3d(-25px, 0, 0);
  }

  75% {
    transform: translate3d(10px, 0, 0);
  }

  90% {
    transform: translate3d(-5px, 0, 0);
  }

  100% {
    opacity: 1;
    transform: none;
  }
}

/* 水位球样式 Create by trainer 2023/07/23 */
.water-circle {
  margin: 20px auto;
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  border: 3px solid rgb(246, 247, 248);
  box-shadow: 0 0 10px #007bff;
}

.water {
  position: absolute;

  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgb(23, 106, 201);
  border-radius: 50%;
  overflow: hidden;
}

.water::after {
  content: '';
  position: absolute;
  top: var(--remaining-space);

  left: 50%;
  width: 150%;
  height: 150%;
  border-radius: 40%;
  background-color: rgb(240, 228, 228);
  animation: real 5s linear infinite;
}

@keyframes real {
  0% {
    transform: translate(-50%, -65%) rotate(0deg);
  }

  100% {
    transform: translate(-50%, -65%) rotate(360deg);
  }
}

/* 水位高度top: 35% ~ -65% */
.water::before {
  content: '';
  position: absolute;
  top: var(--remaining-space);
  left: 50%;
  width: 150%;
  height: 150%;
  border-radius: 42%;
  background-color: #007bff;
  animation: virtual 7s linear infinite;
}

@keyframes virtual {
  0% {
    transform: translate(-50%, -60%) rotate(0deg);
  }

  100% {
    transform: translate(-50%, -60%) rotate(360deg);
  }
}

/* 定制浮动水位样式 */
// .water-level-10::after,
// .water-level-10::before {
//   top: 0%;
// }
.move-initial {
  // transition: transform 3s ease-in-out;
  transform: translateX(0);
}

.move-right {
  // transition: transform 3s ease-in-out;
  transform: translateX(1.2rem);
}

.move-left {
  // transition: transform 3s ease-in-out;
  transform: translateX(-1.2rem);
}

.move-right-vent {
  // transition: transform 3s ease-in-out;
  transform: translateX(0.5rem);
}

.move-left-vent {
  // transition: transform 3s ease-in-out;
  transform: translateX(-0.5rem);
}
</style>
